// var Bmob = require('../../utils/bmob.js');
var that;
let App = getApp();
// 最大行数
var max_row_height = 5;
// 行高
var cart_offset = 90;
// 底部栏偏移量
var food_row_height = 49;
Page({
	data: {
		categoryId:'',//分类id
		indicatorDots: true, //是否显示面板指示点
		autoplay: true,
		interval: 2000, //自动切换时间间隔
		duration: 1000, //滑动动画时长
		indicatorColor: "rgba(255,255,255,.4)", //普通轮播点背景色
		indicatorActiveColor: "#fff", //选中轮播点背景色
		imgUrls: [],
		imgs: '',
		categoryStates: [],
		cartData: {},
		maskVisual: 'hidden',
		amount: 0,
		quantity:2,
		foodObjects: [],//
		categoryObjects:[],
		cartObjects:[],
		maskyq:false,
		index:0,
		cate_id:'',
		user:'',
		mobile:'',
		currentCampus:0,
		cartinfo:''
		
	},
	// 关闭邀请弹窗
	close_yq(){
		this.setData({
			maskyq:false
		})
	},
	// 输入推荐码
	mobile(e){
		this.setData({
			mobile:e.detail.value
		})
	},
	// 填写邀请码
	addInviteCode(){
		
		that = this;
		if (that.data.mobile == '') {
		    wx.showModal({
		        title: '请填邀请码',
		        showCancel: false
		    });
		    return;
		}
		wx.request({
			url: App.url.requestUrl + 'user/addInviteCode',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType: 'json',
			data:{mobile:that.data.mobile},
			success: function (res) {
			  if(res.data.ret == 200){
					 that.setData({
					 	maskyq:false
					 })
					 wx.showToast({
					   title: '添加成功',
					   icon: 'success',
					   duration: 2000
					 })
					 
				 }else{
					 that.setData({
					 	maskyq:false
					 })
					wx.showToast({
					  title: res.data.msg,
					  icon: 'none',
					  duration: 2000
					}) 
				 }
			}
		})
	},
	
	
	
	
	
	// 判断是否填写邀请
	userInfo(){
		that = this;
		wx.request({
			url: App.url.requestUrl + 'user/userInfo',
			method: 'POST',
			header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			success: function (res) {
			  if(res.data.ret == 200){
          console.log(res.data.data.level)
          if (res.data.data.level==0){
					  that.setData({
              maskyq:true
					  })  
				  }else{
					   that.setData({
               maskyq: false
					   }) 
					
				 }
				
			}else if(res.data.code == 401){
				setTimeout(function(){
				  wx.navigateTo({
				    url: '../../login/phone/phone',
				  })
				},2500)
			}
			}
		})
	},
	// banner
	banner(){
		that = this;
		wx.request({
			url: App.url.requestUrl + 'index/getBanner',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			
			success: function (res) {
			  if(res.data.ret == 200){
					that.setData({
					  imgUrls:res.data.data
					})  
				 }
			}
		})
	},
	// 获取分类
	categoryObjects(){
		that = this;
		wx.request({
			url: App.url.requestUrl + 'index/cateList',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			
			success: function (res) {
			  if(res.data.ret == 200){
				 wx.setStorageSync('cate_id',res.data.data[0].id);
					that.setData({
					 categoryObjects:res.data.data,
					 cate_id:res.data.data[0].id
					})  
				 }
			}
		})
	},
	//获取分类产品
	foodObjects(cate_id){
    if (!cate_id){
      cate_id = wx.getStorageSync('cate_id')
    }
		that = this;
		wx.request({
			url: App.url.requestUrl + 'index/goodsByCate',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			data:{
				page:1,
				cate_id:cate_id
			},
			success: function (res) {
			  if(res.data.ret == 200){
					that.setData({
					 foodObjects:res.data.data
					})  
				 }
			}
		})
	},
	//获取购物车
	getlists(){
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/getlists',
			method: 'POST',
			header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			success: function (res) {
			  if(res.data.ret == 200){
				  if(res.data.data.goods_list.length>0){
					  that.setData({
						quantity:2,
						cartinfo:res.data.data,
					    cartObjects:res.data.data.goods_list
					  })  
				  }else{
					  that.setData({
					  	quantity:0,
						cartObjects:[]					  
						})  
				    }
				}
			}
		})
	},
	onLoad: function(options) {
    var that = this
    console.log(that.data.cate_id)
    that.categoryObjects()//获取分类
		that = this;
		that.banner()//banner
    that.userInfo()//获取是否填写邀请
    that.getlists()//获取购物车
		setTimeout(function(){
      that.foodObjects(that.data.cate_id)
    },1000)
	
	
	
	},
    // 获取分类id并切换分类
	switchCategory: function(e) {
		var index = e.currentTarget.dataset.index;
		var categoryId = e.currentTarget.dataset.id;
    console.log(categoryId)
		var categoryStates = that.data.categoryStates;
		categoryStates = categoryStates.map(function(item, i) {
			if (index == i) {
				item = true;
			} else {
				item = false;
			}
			return item;
		});
		that.setData({
			'currentCampus': index,
			categoryId:categoryId
		});
		
		that.foodObjects(categoryId);
	},
	checkout: function() {
		// 将对象序列化
		var cartObjects = [];
		that.data.cartObjects.forEach(function(item, index) {
			console.log(item)
			console.log(index)
			var cart = {
				goods_id: item.goods_id,
				goods_num: item.total_num,
				// quantity: item.quantity
			};
			cartObjects.push(cart);
			console.log(cartObjects)
		});

		wx.navigateTo({
			url: '../../order/checkout/checkout?carts=' + JSON.stringify(cartObjects)
		});
	},
	add: function(e) {
		// 所点商品id
		var cartData = that.data.cartData;
		var goods_id = e.currentTarget.dataset.foodId;
		var goods_num = e.currentTarget.dataset.num;
		++goods_num;
		that.cartToArrayadd(goods_id,goods_num);
		
	},
	subtract: function(e) {
		// 所点商品id
		var goods_id = e.currentTarget.dataset.foodId;
		var goods_num = e.currentTarget.dataset.num;
		--goods_num;
		console.log(goods_num)
		if(goods_num>=1){
			that.cartToArraycut(goods_id);
		}else if(goods_num=1){
			that.dellgoods(goods_id);
		}
	},
	cartToArrayadd(goods_id,goods_num) {
		// 需要判断购物车数据中是否已经包含了原商品，从而决定新添加还是仅修改它的数量
		var cartData = that.data.cartData;
		var cartObjects = that.data.cartObjects;
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/add',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			data:{
				goods_id:goods_id,
				goods_num:1
			},
			success: function (res) {
			  if(res.data.ret == 200){
         
				 that.getlists()
				 that.foodObjects(that.data.categoryId)
			    }
			}
		})
	},
	cartToArraycut(goods_id) {
		// 需要判断购物车数据中是否已经包含了原商品，从而决定新添加还是仅修改它的数量
		var cartData = that.data.cartData;
		var cartObjects = that.data.cartObjects;
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/sub',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			data:{
				goods_id:goods_id
			},
			success: function (res) {
			  if(res.data.ret == 200){
				 that.getlists()
				 that.foodObjects(that.data.categoryId)
			    }
			}
		})
	},
	dellgoods(goods_id){
		var cartData = that.data.cartData;
		var cartObjects = that.data.cartObjects;
		that = this;
		wx.request({
			url: App.url.requestUrl + 'Cart/delete',
			method: 'POST',
			 header: {'content-type': 'application/x-www-form-urlencoded',"token":wx.getStorageSync('access_token')},
			dataType:'json',
			data:{
				goods_id:goods_id
			},
			success: function (res) {
			  if(res.data.ret == 200){
				 that.getlists()
				  that.foodObjects(that.data.categoryId)
			    }
			}
		})
	},
	
	
	cascadeToggle: function () {
	  //切换购物车开与关
	  // console.log(that.data.maskVisual);
	  if (that.data.maskVisual == 'show') {
	    that.cascadeDismiss();
	  } else {
	    that.cascadePopup();
	  }
	},
	cascadePopup: function () {
	  // 购物车打开动画
	  var animation = wx.createAnimation({
	    duration: 300,
	    timingFunction: 'ease-in-out',
	  });
	  that.animation = animation;
	  // scrollHeight为商品列表本身的高度
	  var scrollHeight = (that.data.cartObjects.length <= max_row_height ? that.data.cartObjects.length : max_row_height) *
	    food_row_height;
	  // cartHeight为整个购物车的高度，也就是包含了标题栏与底部栏的高度
	  var cartHeight = scrollHeight + cart_offset;
	  animation.translateY(-cartHeight).step();
	  that.setData({
	    animationData: that.animation.export(),
	    maskVisual: 'show',
	    scrollHeight: scrollHeight,
	    cartHeight: cartHeight
	  });
	  // 遮罩渐变动画
	  var animationMask = wx.createAnimation({
	    duration: 150,
	    timingFunction: 'linear',
	  });
	  that.animationMask = animationMask;
	  animationMask.opacity(0.8).step();
	  that.setData({
	    animationMask: that.animationMask.export(),
	  });
	},
	cascadeDismiss: function () {
	  // 购物车关闭动画
	  that.animation.translateY(that.data.cartHeight).step();
	  that.setData({
	    animationData: that.animation.export()
	  });
	  // 遮罩渐变动画
	  that.animationMask.opacity(0).step();
	  that.setData({
	    animationMask: that.animationMask.export(),
	  });
	  // 隐藏遮罩层
	  that.setData({
	    maskVisual: 'hidden'
	  });
	},
	amount: function () {
	  var cartObjects = that.data.cartObjects;
	  var amount = 0;
	  var quantity = 0;
	  cartObjects.forEach(function (item, index) {
	    amount += item.quantity * item.food.get('price');
	    quantity += item.quantity;
	  });
	  that.setData({
	    amount: amount.toFixed(2),
	    quantity: quantity
	  });
	},
	onShareAppMessage: function (res) {
	  console.log(123)
	  if (res.from === 'button') {
	    // 来自页面内转发按钮
	  }
	  return {
	    title: "辅本固正",
	    path: '/login/login/login?id='+123 
	  }
	},
	onShow: function () {
    this.foodObjects(wx.getStorageSync('cate_id'))
		this.getlists()
	
	    this.setData({
			currentCampus:0
		})
	},
})
